const doc = window.document;

/**
 *
 * @param key
 */
function get(key){
    if(!key || !_has(key)){
        let regexpStr =
            "(?:^|.*;\\s*)" +
            escape(key).replace(/[-.+*]/g, "\\$&") +
            "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*";
        return JSON.parse(unescape(doc.cookie.replace(new RegExp(regexpStr), "$1")));
    }
}

/**
 * 设置cookie
 * @param key
 * @param data
 */
function set(key, data){
    if(!key){
        return;
    }
    data = JSON.stringify(data);
    doc.cookie = escape(key) + "=" + escape(data) + ";path=/";
}

/**
 * 设置key失效
 * @param key
 */
function remove(key) {
    if(!key || !_has(key)){
        return;
    }
    doc.cookie = escape(key)+"=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
}
/**
 *
 * @param key
 * @private
 */
function _has(key){
    return new RegExp("(?:^|;\\s*)" + escape(key).replace(/[-.+*]/g, "\\$&") + "\\s*\\=").test(doc.cookie);
}

export default {
    get,
    set,
    remove,
    has: _has
}